package com.example.administrator.runbook.fragments.community.utils;

import android.os.Environment;

import com.example.administrator.runbook.BuildConfig;
import com.example.administrator.runbook.MainApplication;
import com.jakewharton.disklrucache.DiskLruCache;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;

/**
 * Created by Administrator on 2016/11/9.
 */

public class DiskCache {

    /**
     * 得到缓存路径
     * @param uniqueName
     * @return
     */
    private static File getDiskCacheDir(String uniqueName) {
        String cachePath;
        MainApplication context = MainApplication.getInstance();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    public static DiskLruCache getDiskLruCache(String fileName) {
        DiskLruCache mDiskLruCache = null;
        try {
            File cacheDir = getDiskCacheDir(fileName);
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            mDiskLruCache = DiskLruCache.open(
                    cacheDir, BuildConfig.VERSION_CODE, 1, 10 * 1024 * 1024
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mDiskLruCache;
    }

    public static String getMD5(String str) {

        String s = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes("utf-8"));
            s = bytesToHexString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i(s);
        return s;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
